﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;
using GTServices.Entities;
using System.Reflection;
using System.Data.Objects;
using System.Data;



namespace GTServices.Entities
{
    public class RepositoryFactory<TContext> where TContext : DbContext
    {

        public TContext Context { get; set; }

        public RepositoryFactory(TContext context)
        {
            this.Context = context;
        }

        public bool TryGetRespository<TEntity>(out Repository<TEntity, TContext> repo)
            where TEntity : BaseEntity
        {

            repo = null;
            return false;
        }

        public Repository<TEntity, TContext> GetRepository<TEntity>()
            where TEntity : BaseEntity
        {
            if (Context != null)
            {
                return new Repository<TEntity, TContext>(this.Context);
            }
            else
            {
                return null;
            }
        }

        public Repository<TContext> GetRepository(Object obj)
        {
            return GetRepository(GetUnderlyingProxyType(obj));
        }

        public Repository<TContext> GetRepository(Type fromType)
        {
            if (Context != null)
            {
                //The type maybe a dynamic type. So I'll need to resolve the real type. 
                return new Repository<TContext>(this.Context, ObjectContext.GetObjectType(fromType));
            }
            else
            {
                return null;
            }
        }

        public Repository<TContext> GetRepository(String typeName)
        {
            Assembly ass =  Assembly.GetAssembly(this.GetType()); 
            Type t =  ass.GetType(this.GetType().Namespace + "." + typeName); 
            if(t  != null){
                return new Repository<TContext>(this.Context, t); 
            }
            return null;
        }

        public Type GetUnderlyingProxyType(object o)
        {
            return ObjectContext.GetObjectType(o.GetType()); 
        }
        public void SaveAllChanges()
        {
            this.Context.SaveChanges(); 
        }

    }
}
